import { ParameterItemType } from './interface';

const tansfromParams = (
  item: ParameterItemType[],
  prve: ParameterItemType[],
): ParameterItemType[] => {
  const commonArr = item.filter((obj) =>
    prve.some((obj1) => {
      if (obj.filterComponent.compType === 'DATE') {
        return (
          obj.code === obj1.code &&
          obj.filterComponent.compType === obj1.filterComponent.compType &&
          obj.filterComponent.code === obj1.filterComponent.code
        );
      } else {
        return (
          obj.code === obj1.code &&
          obj.filterComponent.compType === obj1.filterComponent.compType
        );
      }
    }),
  );
  // console.log(commonArr)
  if (commonArr.length > 0) {
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < prve.length; i++) {
      // eslint-disable-next-line array-callback-return
      const findItem = commonArr.find((value: any) => {
        if (prve[i].filterComponent.compType === 'DATE') {
          if (
            value.code === prve[i].code &&
            value.filterComponent.comType ===
              prve[i].filterComponent.compType &&
            value.filterComponent.code === prve[i].filterComponent.code
          ) {
            return value;
          }
        } else if (
          value.code === prve[i].code &&
          value.filterComponent.comType === prve[i].filterComponent.compType
        ) {
          return value;
        }
      });
      // console.log(findItem)
      if (findItem !== undefined) {
        prve[i] = handleCovertValue(findItem, prve[i]);
      }
    }
    return prve;
  } else {
    return prve;
  }
};

const handleCovertValue = (covertValue, originVal) => {
  if (originVal.filterComponent.compType === 'DATE') {
    switch (originVal.type) {
      case 'SINGLE_VALUE':
        if (covertValue.type === 'SINGLE_VALUE') {
          originVal.value = covertValue.value;
        } else if (covertValue.type === 'MULTI_VALUE') {
          originVal.value = covertValue.endValue;
        }
        break;
      case 'MULTI_VALUE':
        if (covertValue.type === 'SINGLE_VALUE') {
          originVal.endValue = covertValue.value;
        } else if (covertValue.type === 'MULTI_VALUE') {
          originVal.startValue = covertValue.startValue;
          originVal.endValue = covertValue.endValue;
        }
        break;
      default:
        return originVal;
    }
  } else {
    originVal.value = covertValue.value;
  }
  return originVal;
};

export default tansfromParams;
